<?php
/**
 * @Name: AuthAdminToken.php
 * @Author: yashuai<1762910894@qq.com>
 */

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Http\Model\Rbac\UserModel;
use App\Http\Logic\Rbac\UserTokenLogic;
use HugCode\PhpUnits\Frame\Code\ConstCode;

class AuthAdminToken
{

    /**
     * @param Request $request
     * @param Closure $next
     * @return mixed
     * @throws \App\Exceptions\ThrowException
     * @author yashuai<1762910894@qq.com>
     */
    public function handle(Request $request, Closure $next)
    {
        $token = $request->header('token', $request->get('token', false));
        //  token 验证
        $result = UserTokenLogic::instance()->id($token);
        if ($result === false) {
            _throw('登录异常', 107000);
        }

        $userInfo = UserModel::getInfo($result['UserID'], 'UserID', ['UserID', 'IsSuper', 'UserStatus']);
        if (empty($userInfo) || $userInfo['UserStatus'] != ConstCode::BASIC_STATUS_NORMAL) {
            _throw('登录异常：当前用户不存在', 107000);
        }

        // 权限验证
        $power = UserTokenLogic::instance()->validatorNodePower($userInfo);
        if ($power !== true) {
            _throw('无权限访问接口：' . implode('.', _controller_action()), 107004);
        }

        $request->userId = $result['UserID'];
        $request->delayed = $result['Delayed'];
        return $next($request);
    }

}


